
import os
import re
import requests

def mkdir_if_not_exist(path:str):
    """
    保证目录存在
    """
    if not os.path.exists(path):
        os.makedirs(path)

def clean_file_name(filename:str):
    """
    清理文件名称,使其满足mac的文件命名规则
    """
    invalid_chars='[,\\\/:*?"<>|]'
    replace_char=''
    return re.sub(invalid_chars,replace_char,filename)

def format_title(name:str) -> str:
    def pick_str(name:str) -> str:
        special_strs = [ "_", "-" ]
        return "".join([ s for s in name if s.isdigit() or s.lower().isalpha() or s in special_strs ])
    splis:list[str] = [ seg.strip() for seg in name.split(" ") ]
    splis:list[str] = [ pick_str(seg) for seg in splis if len(seg) > 0  ]
    splis:list[str] = [ s for s in splis if len(s) > 0 ]
    return " ".join(splis)

def delete_all_files_in_directory(directory):
    if not os.path.exists(directory):
        print(f"directory is not exsit: {directory}")
        return
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                os.remove(file_path)
            except Exception as e:
                print(f"connot delete file: {file_path}: {e}")


def download_pdf(url, save_dir, filename):
    """
    从给定 URL 下载 PDF 文件并保存到指定目录。

    参数:
    - url: PDF 文件的下载链接
    - save_dir: 保存文件的目录
    - filename: 保存的文件名（包括 .pdf 扩展名）
    """
    # 确保保存目录存在
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    # 拼接保存路径
    file_path = os.path.join(save_dir, filename)

    # 使用流式下载方式下载文件
    with requests.get(url, stream=True) as response:
        # 检查请求是否成功
        if response.status_code == 200:
            # 打开文件进行写入
            with open(file_path, 'wb') as f:
                # 逐块下载并写入文件
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)
            print(f"文件已成功下载并保存到: {file_path}")
        else:
            print(f"下载失败, HTTP 状态码: {response.status_code}")

def get_file_size(file_path):
    if os.path.isfile(file_path):
        file_size = os.path.getsize(file_path)
        return file_size
    else:
        # 文件不存在
        return -1
